<template>
  <div>
    <Form inline
      ref="filterValidate"
      :model="filterValidate"
      :rules="ruleValidate"
      :label-width="150">
      <FormItem label="会员等级:" prop="memberLevels">
        <Select v-model="filterValidate.memberLevels" multiple :max-tag-count="4" :max-tag-placeholder="maxTagPlaceholder">
          <Option v-for="(item, index) in memberLevelList"
                  :value="item.memberLevel"
                  :key="index">
            V{{ item.memberLevel }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="SVIP会员:" prop="superMember">
        <Select v-model="filterValidate.superMember">
          <Option v-for="(item, index) in [{ label: '全部', value: 2 }, { label: '是', value: 0 }, { label: '否', value: 1 }]"
                  :value="item.value"
                  :key="index">
            {{ item.label }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="注册门店:" prop="registerShopIds">
        <vueTreeselectChoice :multiple="true" :width='280'
          ref="vueTreeselectChoice"
          @input="handleShop"
          v-model="filterValidate.registerShopIds"></vueTreeselectChoice>
      </FormItem>
      <FormItem label="第一次消费门店:" prop="consumerShopIds">
        <vueTreeselectChoice :multiple="true" :width='280'
          ref="vueTreeselectChoice2"
          @input="handleShop2"
          v-model="filterValidate.consumerShopIds"></vueTreeselectChoice>
      </FormItem>
      <FormItem label="注册起止日期:" prop="registerDate">
        <DatePicker v-model="filterValidate.registerDate" format="yyyy-MM-dd HH:mm:ss" type="datetimerange" placeholder="请选择" style="width: 280px" @on-change="registerDateChange" @on-clear="filterValidate.registerDate = []"></DatePicker>
      </FormItem>
      <FormItem label="生日起止日期:" prop="birthdayDate">
        <DatePicker v-model="filterValidate.birthdayDate" type="daterange" placeholder="请选择" style="width: 280px" @on-change="birthdayDateChange" @on-clear="filterValidate.birthdayDate = []"></DatePicker>
      </FormItem>
      <FormItem label="剩余可用游戏币:" style="width: 830px" prop="coinAmount">
        <div class="filter-flex">
          <Input placeholder="请输入" v-model="filterValidate.coinStartAmount" class="input-wid" :maxlength="9" @on-keyup="filterSpace('coinStartAmount')" @on-blur="filterSpace('coinStartAmount')" />
          <span style="padding: 0 10px">-</span>
          <Input placeholder="请输入" v-model="filterValidate.coinEndAmount" class="input-wid" :maxlength="9" @on-keyup="filterSpace('coinEndAmount')" @on-blur="filterSpace('coinEndAmount')" />
        </div>
      </FormItem>
      <FormItem label="剩余可用彩票:" style="width: 830px" prop="lotteryAmount">
        <div class="filter-flex">
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.lotteryStartAmount" @on-keyup="filterSpace('lotteryStartAmount')" @on-blur="filterSpace('lotteryStartAmount')" />
          <span style="padding: 0 10px">-</span>
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.lotteryEndAmount" @on-keyup="filterSpace('lotteryEndAmount')" @on-blur="filterSpace('lotteryEndAmount')" />
        </div>
      </FormItem>
      <FormItem label="剩余可用积分:" style="width: 830px" prop="integralAmount">
        <div class="filter-flex">
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.integralStartAmount" @on-keyup="filterSpace('integralStartAmount')" @on-blur="filterSpace('integralStartAmount')" />
          <span style="padding: 0 10px">-</span>
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.integralEndAmount" @on-keyup="filterSpace('integralEndAmount')" @on-blur="filterSpace('integralEndAmount')"/>
        </div>
      </FormItem>
      <FormItem label="第一次消费金额:" style="width: 830px" prop="consumeAmount">
        <div class="filter-flex">
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeStartAmount" @on-keyup="filterSpace('consumeStartAmount')" @on-blur="filterSpace('consumeStartAmount')" />
          <span style="padding: 0 10px">-</span>
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeEndAmount" @on-keyup="filterSpace('consumeEndAmount')" @on-blur="filterSpace('consumeEndAmount')" />
        </div>
      </FormItem>
      <FormItem label="消费起止时间:" prop="consumeDate">
        <DatePicker v-model="filterValidate.consumeDate" format="yyyy-MM-dd HH:mm:ss" @on-change="consumeDateChange" @on-clear="filterValidate.consumeDate = []" type="datetimerange" placeholder="请选择" style="width: 280px"></DatePicker>
      </FormItem>
      <FormItem></FormItem>
      <FormItem label="消费频次(最近六个月):" style="width: 830px" prop="consumeMonthTime">
        <div class="filter-flex">
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeStartMonthTime" @on-keyup="filterSpace('consumeStartMonthTime')" @on-blur="filterSpace('consumeStartMonthTime')" />
          <span style="padding: 0 10px">-</span>
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeEndMonthTime" @on-keyup="filterSpace('consumeEndMonthTime')" @on-blur="filterSpace('consumeEndMonthTime')" />
        </div>
      </FormItem>
      <FormItem label="消费频次(最近一年):" style="width: 830px" prop="consumeYearTime">
        <div class="filter-flex">
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeStartYearTime" @on-keyup="filterSpace('consumeStartYearTime')" @on-blur="filterSpace('consumeStartYearTime')" />
          <span style="padding: 0 10px">-</span>
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeEndYearTime" @on-keyup="filterSpace('consumeEndYearTime')" @on-blur="filterSpace('consumeEndYearTime')" />
        </div>
      </FormItem>
      <FormItem label="总消费额(最近六个月):" style="width: 830px" prop="consumeMonthAmount">
        <div class="filter-flex">
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeStartMonthAmount" @on-keyup="filterSpace('consumeStartMonthAmount')" @on-blur="filterSpace('consumeStartMonthAmount')" />
          <span style="padding: 0 10px">-</span>
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeEndMonthAmount" @on-keyup="filterSpace('consumeEndMonthAmount')" @on-blur="filterSpace('consumeEndMonthAmount')" />
        </div>
      </FormItem>
      <FormItem label="总消费额(最近一年):" style="width: 830px" prop="consumeYearAmount">
        <div class="filter-flex">
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeStartYearAmount" @on-keyup="filterSpace('consumeStartYearAmount')" @on-blur="filterSpace('consumeStartYearAmount')" />
          <span style="padding: 0 10px">-</span>
          <Input placeholder="请输入" class="input-wid" :maxlength="9" v-model="filterValidate.consumeEndYearAmount" @on-keyup="filterSpace('consumeEndYearAmount')" @on-blur="filterSpace('consumeEndYearAmount')" />
        </div>
      </FormItem>
      <FormItem style="width: 830px">
        <div class="filter-flex">
          <Input disabled class="input-wid" v-model="member" />
          <span style="padding: 0 10px; visibility: hidden">-</span>
          <Button type="primary"
            @click="filterMember"
          >按筛选统计会员数量</Button>
        </div>
      </FormItem>
      <FormItem class="form-btn"
                style="margin-top: 5px;">
        <Button type="primary"
                class="system-submit-btn"
                @click="handleSubmit"
                >确定</Button>
        <Button class="system-submit-btn"
                @click="handleReset"
                style="margin-left: 8px">取消</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getMemberLevelList } from '@/api/member/index'
import { memberFilter } from '@/api/market/smartcoupon'
import vueTreeselectChoice from '@/components/vue-treeselect-choice/index.js'
export default {
  name: 'filterMember',
  components: {
    vueTreeselectChoice
  },
  data () {
    return {
      lock: true,
      memberLevelList: [],
      filterValidate: {
        memberLevels: [],
        superMember: '',
        registerShopIds: [],
        consumerShopIds: [],
        registerDate: [],
        birthdayDate: [],
        coinStartAmount: '',
        coinEndAmount: '',
        lotteryStartAmount: '',
        lotteryEndAmount: '',
        integralStartAmount: '',
        integralEndAmount: '',
        consumeStartAmount: '',
        consumeEndAmount: '',
        consumeDate: [],
        consumeStartMonthTime: '',
        consumeEndMonthTime: '',
        consumeStartYearTime: '',
        consumeEndYearTime: '',
        consumeStartMonthAmount: '',
        consumeEndMonthAmount: '',
        consumeStartYearAmount: '',
        consumeEndYearAmount: ''
      },
      ruleValidate: {
        memberLevels: { required: true, message: '请选择会员等级' },
        superMember: { required: true, message: '请选择是否SVIP会员' },
        registerDate: { required: true,
          validator: (rule, value, callback) => {
            if (this.filterValidate.registerDate.length && this.filterValidate.registerDate[1]) {
              callback()
            } else {
              callback(new Error('请选择注册起止时间'))
            }
          }
        },
        coinAmount: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            this.validateRequire(this.filterValidate.coinStartAmount, this.filterValidate.coinEndAmount, '请输入剩余可用游戏币', callback)
          }
        },
        lotteryAmount: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            this.validateRequire(this.filterValidate.lotteryStartAmount, this.filterValidate.lotteryEndAmount, '请输入剩余可用彩票', callback)
          }
        },
        integralAmount: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            this.validateRequire(this.filterValidate.integralStartAmount, this.filterValidate.integralEndAmount, '请输入剩余可用积分', callback)
          }
        },
        consumeAmount: {
          trigger: 'blur',
          validator: (rule, value, callback) => {
            this.validate(this.filterValidate.consumeStartAmount, this.filterValidate.consumeEndAmount, '请输入第一次消费金额', callback)
          }
        },
        consumeMonthTime: {
          trigger: 'blur',
          validator: (rule, value, callback) => {
            this.validate(this.filterValidate.consumeStartMonthTime, this.filterValidate.consumeEndMonthTime, '请输入消费频次(最近六个月)', callback)
          }
        },
        consumeYearTime: {
          trigger: 'blur',
          validator: (rule, value, callback) => {
            this.validate(this.filterValidate.consumeStartYearTime, this.filterValidate.consumeEndYearTime, '请输入消费频次(最近一年)', callback)
          }
        },
        consumeMonthAmount: {
          trigger: 'blur',
          validator: (rule, value, callback) => {
            this.validate(this.filterValidate.consumeStartMonthAmount, this.filterValidate.consumeEndMonthAmount, '请输入总消费额(最近六个月)', callback)
          }
        },
        consumeYearAmount: {
          trigger: 'blur',
          validator: (rule, value, callback) => {
            this.validate(this.filterValidate.consumeStartYearAmount, this.filterValidate.consumeEndYearAmount, '请输入总消费额(最近一年)', callback)
          }
        }
      },
      member: ''
    }
  },
  props: ['formData', 'memberNum'],
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId
    })
  },
  watch: {
    formData (val) {
      this.filterValidate = {
        memberLevels: val.memberLevels,
        superMember: val.superMember,
        registerShopIds: val.registerShopIds || [],
        consumerShopIds: val.consumerShopIds || [],
        registerDate: [val.registerStartDate, val.registerEndDate],
        birthdayDate: val.birthdayStartDate ? [val.birthdayStartDate, val.birthdayEndDate] : [],
        coinStartAmount: val.coinStartAmount + '',
        coinEndAmount: val.coinEndAmount + '',
        lotteryStartAmount: val.lotteryStartAmount + '',
        lotteryEndAmount: val.lotteryEndAmount + '',
        integralStartAmount: val.integralStartAmount + '',
        integralEndAmount: val.integralEndAmount + '',
        consumeStartAmount: val.consumeStartAmount === null ? '' : val.consumeStartAmount + '',
        consumeEndAmount: val.consumeEndAmount === null ? '' : val.consumeEndAmount + '',
        consumeDate: val.consumeStartDate ? [val.consumeStartDate, val.consumeEndDate] : [],
        consumeStartMonthTime: val.consumeStartMonthTime === null ? '' : val.consumeStartMonthTime + '',
        consumeEndMonthTime: val.consumeEndMonthTime === null ? '' : val.consumeEndMonthTime + '',
        consumeStartYearTime: val.consumeStartYearTime === null ? '' : val.consumeStartYearTime + '',
        consumeEndYearTime: val.consumeEndYearTime === null ? '' : val.consumeEndYearTime + '',
        consumeStartMonthAmount: val.consumeStartMonthAmount === null ? '' : val.consumeStartMonthAmount + '',
        consumeEndMonthAmount: val.consumeEndMonthAmount === null ? '' : val.consumeEndMonthAmount + '',
        consumeStartYearAmount: val.consumeStartYearAmount === null ? '' : val.consumeStartYearAmount + '',
        consumeEndYearAmount: val.consumeEndYearAmount === null ? '' : val.consumeEndYearAmount + ''
      }
      setTimeout(() => {
        this.lock = false
      }, 300)
    },
    memberNum (val) {
      this.member = val
    }
  },
  mounted () {
    this.getMemberLevel()
  },
  methods: {
    // 查询会员等级
    getMemberLevel () {
      getMemberLevelList({
        merchantId: this.merchantId
      }).then(res => {
        if (res.data.status === 200) {
          this.memberLevelList = res.data.data || []
          if (this.memberLevelList.length > 0) {
            this.memberLevelList = this.memberLevelList.map(item => {
              return { memberLevel: item.memberLevel }
            })
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    getMembers () {
      const params = this.getParams()
      return new Promise((resolve, reject) => {
        memberFilter(params).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            resolve(result.totalCount)
          } else {
            this.$Message.error(`${result.error}`)
            reject(new Error('err'))
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
          reject(new Error('err'))
        })
      })
    },
    getParams () {
      const filterValidate = this.filterValidate
      const params = {
        merchantId: this.merchantId,
        memberLevels: filterValidate.memberLevels,
        superMember: filterValidate.superMember,
        registerShopIds: filterValidate.registerShopIds || [],
        consumerShopIds: filterValidate.consumerShopIds || [],
        registerStartDate: this.formDate(filterValidate.registerDate[0]),
        registerEndDate: this.formDate(filterValidate.registerDate[1]),
        birthdayStartDate: this.formDate(filterValidate.birthdayDate[0]),
        birthdayEndDate: this.formDate(filterValidate.birthdayDate[1]),
        coinStartAmount: +filterValidate.coinStartAmount,
        coinEndAmount: +filterValidate.coinEndAmount,
        lotteryStartAmount: +filterValidate.lotteryStartAmount,
        lotteryEndAmount: +filterValidate.lotteryEndAmount,
        integralStartAmount: +filterValidate.integralStartAmount,
        integralEndAmount: +filterValidate.integralEndAmount,
        consumeStartAmount: filterValidate.consumeStartAmount ? +filterValidate.consumeStartAmount : '',
        consumeEndAmount: filterValidate.consumeEndAmount ? +filterValidate.consumeEndAmount : '',
        consumeStartDate: this.formDate(filterValidate.consumeDate[0]),
        consumeEndDate: this.formDate(filterValidate.consumeDate[1]),
        consumeStartMonthTime: filterValidate.consumeStartMonthTime ? +filterValidate.consumeStartMonthTime : '',
        consumeEndMonthTime: filterValidate.consumeEndMonthTime ? +filterValidate.consumeEndMonthTime : '',
        consumeStartYearTime: filterValidate.consumeStartYearTime ? +filterValidate.consumeStartYearTime : '',
        consumeEndYearTime: filterValidate.consumeEndYearTime ? +filterValidate.consumeEndYearTime : '',
        consumeStartMonthAmount: filterValidate.consumeStartMonthAmount ? +filterValidate.consumeStartMonthAmount : '',
        consumeEndMonthAmount: filterValidate.consumeEndMonthAmount ? +filterValidate.consumeEndMonthAmount : '',
        consumeStartYearAmount: filterValidate.consumeStartYearAmount ? +filterValidate.consumeStartYearAmount : '',
        consumeEndYearAmount: filterValidate.consumeEndYearAmount ? +filterValidate.consumeEndYearAmount : ''
      }
      return params
    },
    formDate (time) {
      if (time) {
        if (typeof time === 'object') {
          return `${time.getFullYear()}-${this.formatNum(time.getMonth() + 1)}-${this.formatNum(time.getDate())} ${this.formatNum(time.getHours())}:${this.formatNum(time.getMinutes())}:${this.formatNum(time.getSeconds())}`
        } else {
          if (time.split(' ').length > 1) {
            return time
          } else {
            return time + ' 00:00:00'
          }
        }
      } else {
        return ''
      }
    },
    formatNum (num) {
      if (num < 10) {
        return '0' + num
      }
      return num
    },
    filterMember () {
      this.$refs.filterValidate.validate(val => {
        if (val) {
          this.$Spin.show()
          this.getMembers().then(count => {
            this.member = count
            this.$Spin.hide()
          }).catch(() => {
            this.$Spin.hide()
          })
        }
      })
    },
    handleSubmit () {
      if (this.member + '') {
        this.$emit('on-sure', this.member, this.getParams())
      } else {
        this.$Message.error('请先进行筛选')
      }
    },
    handleReset () {
      this.$emit('on-cancel')
    },
    registerDateChange (val) {
      this.filterValidate.registerDate = val
    },
    birthdayDateChange (val) {
      this.filterValidate.birthdayDate = val
    },
    consumeDateChange (val) {
      this.filterValidate.consumeDate = val
    },
    filterSpace (prop) {
      this.filterValidate[prop] = this.filterValidate[prop].replace(/[\D\s]/g, '')
      if (this.filterValidate[prop].length > 1 && this.filterValidate[prop][0] === '0') {
        this.filterValidate[prop] = this.filterValidate[prop].substr(1, 1)
      }
    },
    validateRequire (start, end, msg, callback) {
      if (start && end) {
        if (+start <= +end) {
          callback()
        } else {
          callback(new Error('终止值应该大于起始值'))
        }
      } else {
        callback(new Error(msg))
      }
    },
    validate (start, end, msg, callback) {
      if (start && end) {
        if (+start <= +end) {
          callback()
        } else {
          callback(new Error('终止值应该大于起始值'))
        }
      } else if (!start && !end) {
        callback()
      } else {
        callback(new Error(msg))
      }
    },
    async handleShop () {
      if (this.lock && this.formData) {
        return
      }
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.filterValidate.registerShopIds = ids
    },
    async handleShop2 () {
      if (this.lock && this.formData) {
        return
      }
      const ids = await this.$refs.vueTreeselectChoice2.getShopId()
      this.filterValidate.consumerShopIds = ids
    },
    maxTagPlaceholder (num) {
      return '...'
    }
  }
}
</script>

<style lang="less" scoped>
.filter-flex {
  display: flex;
  align-items: center;
  width: 830px
}
</style>
